/**
 * AUTHOR Creat
 */
package com.gcb.freemarker;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

/**
 * @author Creat
 *
 */
public class Hello extends HttpServlet{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private Configuration cfg;
	
	/**
	 * 
	 */
	public Hello() {
		// TODO Auto-generated constructor stub
	}
	
	
	/* (non-Javadoc)
	 * @see javax.servlet.GenericServlet#init()
	 */
	@Override
	public void init() throws ServletException {
		// TODO Auto-generated method stub
		//初始化FreeMarker配置
        //创建一个Configuration实例
        cfg = new Configuration();
        //设置FreeMarker的模版文件位置
        cfg.setServletContextForTemplateLoading(getServletContext(),"templates");
	}



	/* (non-Javadoc)
	 * @see javax.servlet.http.HttpServlet#service(javax.servlet.ServletRequest, javax.servlet.ServletResponse)
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Override
	public void service(ServletRequest request, ServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		
		//建立数据模型
	    Map root = new HashMap();
	    Set set = new HashSet();
	    set.add("gu");
	    set.add("guvivi");
	    //放入对应数据key value
	    root.put("users",set);
	    //取得模版文件
	    Template t = cfg.getTemplate("hello.ftl");
	    //开始准备生成输出
	    //使用模版文件的charset作为本页面的charset
	    //使用text/html MIME-type
	    response.setContentType("text/html; charset=" + t.getEncoding());
	    PrintWriter out = response.getWriter();
	    
	    //合并数据模型和模版，并将结果输出到out中
	    try {
			t.process(root,out);// 用模板来开发servlet可以只在代码里面加入动态的数据
		} catch (TemplateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw new ServletException("处理Template模版中出现错误", e);
		}
	}
	
	

}
